<template>
	<view class="test">
		<!-- <image src="http://applet.atptest.com/test.jpeg" mode="widthFix"></image> -->
		<view class="main">
			<u--form ref="form" :model="formData" :rules="rules" labelPosition="left">

				<u-form-item prop="imgs">
					<view style="font-size: 32rpx;color: #343434;margin-bottom: 6px;font-weight: 700;">添加鉴别图片</view>
					<view style="font-size: 24rpx;color:#939393;margin-bottom: 10px;">
						在线鉴别受制于照片拍摄角度,光线,图片质量等诸多原因的影响,请您尽可能提供高清图片</view>
					<view style="background-color: #f8f7f7;padding: 20rpx;">
						<uni-file-picker ref="pickerRef" v-model="formData.imgs" fileMediatype="image"
							file-extname="png,jpg" mode="grid" @select="select" @delete="deleteImg" :autoUpload="false"
							limit="9" title="最多选择9张图片"></uni-file-picker>
					</view>
				</u-form-item>

				<u-form-item prop="remark">
					<view style="font-size: 32rpx;color: #343434;margin-bottom: 6px;font-weight: 700;">添加描述</view>
					<view style="font-size: 24rpx;color:#939393;margin-bottom: 10px;">添加更多细节或鉴别期望</view>
					<u--textarea v-model="formData.remark" placeholder="请输入内容" count></u--textarea>
				</u-form-item>
				<u-form-item label="委托方:" labelWidth="120rpx" prop="client" :required="true">
					<u--input v-model="formData.client" placeholder="请输入委托方" border="none"></u--input>
				</u-form-item>
				<u-form-item label="型号:" labelWidth="120rpx" prop="model" :required="true">
					<u--input v-model="formData.model" placeholder="请输入型号" border="none"></u--input>
				</u-form-item>
				<view style="font-size: 24rpx;margin-top: 40rpx;margin-bottom: 20rpx;">
					<u-radio-group v-model="readValue" size="20">
						<u-radio :name="1" shape="square" iconSize="20">
							<span style="color: #AEAEAE;">阅读并同意</span>
							<span style='font-weight: 700;' @click="openClick(8)">《鹏城测试服务协议》</span>
							<span>及</span>
							<span style='font-weight: 700;' @click="openClick(9)">《鉴别规则》</span>
						</u-radio>
					</u-radio-group>
				</view>
				<button @click="formSubmit" :disabled="btnDisabled"
					style="color: #fff;background-color: #3953b8;margin-top: 50rpx;">立即支付(￥{{totalPrice}})</button>
			</u--form>
			<u-toast ref="uToast"></u-toast>
		</view>

		<!-- 通知弹出层 -->
		<u-popup :show="show" :round="30" @close="close" customStyle="overflow-y: scroll;overscroll-behavior: none">
			<view  style="padding: 30rpx;max-height:800rpx;">
				<image src="http://applet.atptest.com/lzc2023082801.jpg" mode="widthFix" style="width: 100%;"></image>
			</view>
		</u-popup>

		<u-popup :show="show1" :round="30" @close="close" customStyle="overflow-y: scroll;overscroll-behavior: none">
			<view style="padding: 30rpx;max-height:800rpx;">
				<image src="http://applet.atptest.com/lzc2023082802.jpg" mode="widthFix" style="width: 100%;"></image>
			</view>
		</u-popup>

		<!-- 跳转提示弹出层 -->
		<u-popup :show="disabledTo" :round="10" mode="center" @close="close">
			<view style="padding: 30rpx;">
				<text v-text="`此单为月结订单,${numTo}秒后自动跳转...`"></text>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	import {
		CreateOrder_Verification,
		GetUserByOpenid,
		GetUserInfo,
	} from '../../../api/user.js'
	import { GetVerificationPrice } from '../../../api/order.js'
	export default {
		data() {
			return {
				// 倒计时2
				timerTo: null,
				numTo: 3,
				disabledTo: false,
				rules: {
					'client': {
						required: true,
						message: '委托方不能为空',
						trigger: ['blur', 'change']
					},
					'model':{
						required: true,
						message: '型号不能为空',
						trigger: ['blur', 'change']
					},
					'imgs': {
						type: 'array',
						min: 1,
						required: true,
						message: '请选择最少1张图片',
						trigger: ['blur', 'change']
					}
				},
				formData: {
					img: [],
					imgs: [],
					remark: '',
					client: '',
					model:''
				},
				totalPrice:0,
				// 上传图片
				// imageValue: [],
				// 订单号
				orderNo: '',
				//判断 采购单号 及 支付
				role: {},
				// 协议弹出层
				readValue: null,
				show: false,
				show1: false,
				//下单按钮禁用
				btnDisabled: false
			};
		},
		methods: {
			...mapMutations('user', ['setToken']),

			// 获取用户身份
			getUserByOpenid() {
				GetUserByOpenid().then((res) => {
					this.role = res
				})
			},
			
			// 获取用户信息
			getUserInfo() {
				GetUserInfo().then((res) => {
					this.formData.client = res.wxName
				})
			},
			
			//获取支付价格
			async getPrice(){
				const res = await GetVerificationPrice()
				console.log("价格",res);
				if(res){
					this.totalPrice = res
				}
			},

			// 调起通知
			subscribe() {
				const _that = this
				uni.getSetting({
					withSubscriptions: true,
					success: (res) => {
						if (!res.subscriptionsSetting.mainSwitch) {
							uni.showModal({
								title: '提示',
								content: '为了及时获取订单状态，您是否想接收订单状态的消息提醒？',
								success: function(res) {
									if (res.confirm) {
										// 订阅消息的总开关,如果是关着的，引导用户去打开
										_that.openMessage()
									} else if (res.cancel) {
										//上传表单信息
										_that.uploadOrder();
									}
								}
							});
						} else {
							// 如果开着，则继续向下打开弹窗，获取用户授权
							_that.message()
						}
					},
					fail() {
						// 如果失败，也打开弹窗，获取用户授权
						_that.message()
					}
				})

			},

			// 调用通知
			message() {
				const _that = this
				uni.requestSubscribeMessage({
					//此处填写刚才申请模板的模板ID
					tmplIds: ['HDW7cwWuKtvWeppBNzrnQiejfi3j18buPzd6lF4CoGs',
						'Xy1xuuzGcV0R5P8Pv8xq7EPb8gHTZAiFwH9OqIM18l0'
					],
					success(res) {
						//上传表单信息
						_that.uploadOrder();
					},
					fail(res) {
						console.log(res);
					}
				})
			},

			// 诱导用户开启订阅
			openMessage() {
				const _that = this
				uni.openSetting({
					withSubscriptions: true,
					complete: (res) => {
						//上传表单信息
						_that.uploadOrder();
						console.log('openMessage');
					}
				})
			},

			// 提交按钮
			formSubmit() {
				//formdata数据校验
				if (this.readValue != 1) {
					this.$refs.uToast.show({
						message: '请先勾选服务协议'
					})
					return
				}
				this.$refs.form.validate().then(res => {
					this.subscribe()
				}).catch(err => {
					this.$refs.uToast.show({
						message: err[0].message
					})
				})
			},

			// 获取上传状态
			select(e) {
				e.tempFiles.forEach((item, index) => {
					// let x = e.tempFiles[0]
					let data = {
						name: item.name,
						extname: item.extname,
						url: item.url,
					}
					if (item.size / 1024 / 1024 < 1.5) {
						this.uploadFiles(item.url, data)
					} else {
						this.comImg(item.url, data)
					}
				})
			},

			// 图片删除
			deleteImg(e) {
				let num = this.formData.imgs.findIndex(v => v.url === e.tempFilePath);
				this.formData.img.splice(num, 1);
			},

			// 图片压缩
			comImg(src, data) {
				uni.compressImage({
					src: src,
					quality: 40,
					success: res => {
						this.uploadFiles(res.tempFilePath, data)
					}
				})
			},

			// 手动调用上传代码
			uploadFiles(tempFilePath, data) {
				console.log('tempFilePath', tempFilePath);
				const _that = this
				return new Promise((resolve) => {
					uni.uploadFile({
						url: 'https://wechat.atptest.com:44387/api/PCApplet/UploadLargeFileOBS',
						filePath: tempFilePath,
						name: 'file',
						// formData: {
						// 	user: 'test'  目前formData自动生成了 file:tempFilePath，如果还向添加其他参数才写
						// },
						success(res) {
							resolve()
							let json_data = JSON.parse(res.data)
							// 上传失败
							if (json_data['errCode'] == 0) {
								return uni.showToast({
									title: json_data['error_message'],
									icon: 'none',
									duration: 2000
								});
							}
							// 上传成功
							_that.formData.img.push(json_data.data)
							_that.formData.imgs.push(data)
						},

					})
				})
			},

			//上传表单信息
			uploadOrder() {
				// 月结
				if (this.role.state) {
					this.formData.state = 9
				} else {
					this.formData.state = 2
				}
				delete this.formData.imgs
				this.btnDisabled = true
				CreateOrder_Verification(this.formData).then((res) => {
						// 订单号
						this.orderNo = res.orderNo

						if (this.formData.state == 9) {
							this.sendTimerTo()
						} else {
							// this.getPay(this.orderNo)

							// 跳转支付详情页
							// uni.navigateTo({
							// 	url: `/pagesA/pages/payOrder/payOrder?i=${this.orderNo}`
							// })
							uni.navigateTo({
								url: `/pagesA/pages/payOrderNew/payOrderNew?i=${this.orderNo}`
							})
						}

						this.formData = {
							img: [],
							imgs: [],
							remark: '',

						}
						// this.imageValue = []
						// 缓存图片清空
						this.$refs.pickerRef.clearFiles()
						this.btnDisabled = false
					})
					.catch((res) => {
						this.btnDisabled = false
					})
			},

			// 关闭弹出层
			close() {
				this.show = false
				this.show1 = false
				// console.log('close');
			},
			// 打开弹出层
			openClick(i) {
				if (i == 8) {
					this.show = true
				} else {
					this.show1 = true
				}
			},

			//月结倒计时
			sendTimerTo() {
				this.numTo = 3
				this.disabledTo = true
				this.loadingTo(); //启动定时器
				this.timerTo = setInterval(() => {
					//创建定时器
					if (this.numTo === 1) {
						this.clearTimerTo(); //关闭定时器
					} else {
						this.loadingTo();
					}
				}, 1000);
			},
			loadingTo() {
				//启动定时器
				this.numTo--; //定时器减1
			},
			clearTimerTo() {
				//清除定时器
				clearInterval(this.timerTo);
				this.timerTo = null;
				this.numTo = '',
					this.disabledTo = false
				uni.navigateTo({
					url: '/pagesB/pages/order/order?i=3'
				})
			},
		},

		onLoad() {
			this.getUserByOpenid()
		},
		onShow() {
			this.getUserInfo()
			this.getPrice()
		},

		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form.setRules(this.rules)
		},
	}
</script>

<style lang="scss" scoped>
	.test {
		.main {
			padding: 0 20rpx;
		}
	}

	/deep/ .file-picker__box-content {
		background-color: #fff !important;
	}
</style>
